package com.vm.db;

import java.util.ArrayList;
import java.util.List;

import com.vm.model.GoodsCollection;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;

public class GoodsCollectionDao {
	private static final String TAG = "GoodsCollectionDao";

	public GoodsCollectionDao(Context context) {
		if (DBOpenHelper.db == null) {
			new DBOpenHelper(context);
		}
	}

	public synchronized void insert(GoodsCollection goodsCollection) {
		Log.d(TAG, "insert");
		try {
			DBOpenHelper.db
					.execSQL(
							"INSERT INTO goodscollection(goodsId,name,imageUrl,price)VALUES(?,?,?,?)",
							new Object[] { goodsCollection.getGoodsId(),
									goodsCollection.getName(),
									goodsCollection.getImageUrl(),
									goodsCollection.getPrice() });
		} catch (Exception e) {
			Log.d(TAG, "insert---" + e.getMessage());
		}
	}

	public synchronized void delete(String goodsId) {
		Log.i(TAG, "delete");
		try {
			DBOpenHelper.db.execSQL(
					"DELETE FROM goodscollection where goodsId=?",
					new Object[] { goodsId });
		} catch (SQLException e) {
			Log.d(TAG, "delete---" + e.getMessage());
		}
	}

	public synchronized List<GoodsCollection> selectall() {
		Log.d(TAG, "selectall");
		List<GoodsCollection> list = new ArrayList<GoodsCollection>();
		Cursor c = null;
		try {
			c = DBOpenHelper.db.rawQuery("SELECT * FROM goodscollection", null);
			while (c.moveToNext()) {
				GoodsCollection goodsCollection = new GoodsCollection();
				goodsCollection = new GoodsCollection();
				goodsCollection.setGoodsId(c.getString(0));
				goodsCollection.setName(c.getString(1));
				goodsCollection.setImageUrl(c.getString(2));
				goodsCollection.setPrice(c.getFloat(3));
				list.add(goodsCollection);
			}
		} catch (SQLException e) {
			Log.d(TAG, "selectall---" + e.getMessage());
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return list;
	}

	public boolean ifExits(String goodsId) {
		Log.d(TAG, "ifExists");
		Cursor c = null;
		try {
			c = DBOpenHelper.db.rawQuery(
					"select * from goodscollection where goodsId=?",
					new String[] { goodsId });
			if (c.moveToNext()) {
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.d(TAG, "ifExists---" + e.getMessage());
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return false;

	}

}